﻿@page "/auth"
@using GMS.NET.Dto.System.Auth.Shared
@using GMS.NET.Web.Components.Service.Interface.System
@using Microsoft.AspNetCore.DataProtection
@using GMS.NET.Encrypt
@using GMS.NET.Web.Components.Shared.Global.Misc
@using GMS.NET.Web.Components.Shared.Global.JsInterop.Cookie
@inject NavigationManager NavigatTo
@inject IAuthService AuthService
@inject ICookie Cookie
@inject IDataProtectionProvider Protector
@layout EmptyLayout
@inject Microsoft.Extensions.Configuration.IConfiguration app

<link href="_content/GMS.NET.Web.Components/css/authrazor.css" rel="stylesheet" />
<section class="gms-workinghny-form">
    <div class="workinghny-form-grid">
        <div class="wrapper">
            <div class="logo">
                <h1><a class="brand-logo" href="#"><span>Working</span> Sign In GMSNET</a></h1>
            </div>
            <div class="workinghny-block-grid">
                <div class="workinghny-left-img align-end">
                    <img src="_content/GMS.NET.Web.Components/images/auth3.png" class="img-responsive" alt="img" />
                </div>
                <div class="form-right-inf">
                    <div style="float:right;margin-bottom:5px;">
                        <Dropdown TValue="string" Items="Items" Color="Color.Info" OnSelectedItemChanged="LoginTypeChanged" />
                    </div>
                    <div class="login-form-content">
                        <div>
                            @if (LogUsr.Mode == LoginType.Default)
                            {
                                <div>
                                    <span style="color: red; font-size: 13px;">@accountVerifyText</span>
                                    <FloatingLabel DisplayText="输入账号wcy" TValue="string" @bind-Value="@LogUsr.Account" IsSelectAllTextOnFocus="true" Color="accountVerifyStatus" />
                                </div>
                                <div>
                                    <span style="color: red; font-size: 13px;">@passwordVerifyText</span>
                                    <FloatingLabel DisplayText="输入密码123456" TValue="string" type="password" @bind-Value="@LogUsr.Password" IsSelectAllTextOnFocus="true" Color="passwordVerifyStatus" />
                                </div>
                            }
                            else if (LogUsr.Mode == LoginType.Email)
                            {
                                <div>
                                    <span style="color: red; font-size: 13px;">@accountVerifyText</span>
                                    <FloatingLabel DisplayText="输入邮箱" TValue="string" @bind-Value="@LogUsr.Account" IsSelectAllTextOnFocus="true"
                                                   Color="accountVerifyStatus" />
                                </div>

                                <div style=" margin-bottom: 15px;">
                                    <span style="color: red; font-size: 13px;">@passwordVerifyText</span>
                                    <BootstrapInputGroup>
                                        <FloatingLabel DisplayText="输入邮箱验证码" TValue="string" @bind-Value="@LogUsr.Password" IsSelectAllTextOnFocus="true" Color="passwordVerifyStatus" style="margin:0;" />
                                        <CountButton Count="60" Color="Color.Info" Icon="fas fa-fw fa-envelope" OnClick="SendEmailCode"
                                                     IsAsync="true"></CountButton>
                                    </BootstrapInputGroup>
                                </div>
                            }
                            else
                            {
                                <div>
                                    <span style="color: red; font-size: 13px;">@accountVerifyText</span>
                                    <FloatingLabel DisplayText="输入手机" TValue="string" @bind-Value="@LogUsr.Account" IsSelectAllTextOnFocus="true"
                                                   Color="accountVerifyStatus" />
                                </div>

                                <div style=" margin-bottom: 15px;">
                                    <span style="color: red; font-size: 13px;">@passwordVerifyText</span>
                                    <BootstrapInputGroup>
                                        <FloatingLabel DisplayText="输入手机验证码" TValue="string" @bind-Value="@LogUsr.Password" IsSelectAllTextOnFocus="true" Color="passwordVerifyStatus" style="margin:0;" />
                                        <CountButton Count="60" Color="Color.Info" Icon="fas fa-fw fa-comment-dots" OnClick="SendPhoneCode"
                                                     IsAsync="true"></CountButton>
                                    </BootstrapInputGroup>
                                </div>
                            }

                            <label class="check-remaind">
                                <input type="checkbox">
                                <span class="checkmark"></span>
                                <p class="remember">当天免登录</p>
                            </label>
                            <Button Text="@btnText" Color="Color.Info" IsBlock="true" IsAsync="true" Icon="fas fa-fw fa-link" OnClick="@SubmitAuth" />
                            <p class="already">没有账号? <a href="#">去注册</a></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="copyright text-center">
        <div class="wrapper">
            <p class="copy-footer-29">
                © 2023 Working Sign In. All rights reserved | Design by <a href="#">GMSNET</a>
            </p>
        </div>
    </div>
</section>


@code{

    private string? publickey { get; set; }

    private IEnumerable<SelectedItem> Items { get; set; } = new List<SelectedItem>()
    {
        new SelectedItem(){ Active=true,Text="默认登陆",Value="0"},
        new SelectedItem(){ Active=false,Text="邮箱登陆",Value="1"},
        new SelectedItem(){ Active=false,Text="手机登陆",Value="2"},
    };
    private Task LoginTypeChanged(SelectedItem Item)
    {
        LogUsr.Mode = (LoginType)Enum.Parse(typeof(LoginType), Item.Value);
        StateHasChanged();
        return Task.CompletedTask;
    }

    protected override Task OnInitializedAsync()
    {
        return base.OnInitializedAsync();
    }
    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            publickey=app.GetSection(EncryptConst.PublicKey).Value ?? "";
            Cookie.RemoveCookie(ClientAppKey.ServerCookie);
        }
        return base.OnAfterRenderAsync(firstRender);
    }
    LoginBasic LogUsr = new LoginBasic();
    string btnText = "登陆";

    private string? EmailCode { get; set; }
    private async Task SendEmailCode()
    {
        EmailCode = ShortId.Create(new());
        var emailInfo = new GMS.NET.Dto.System.Auth.Input.SendEmail() { Email = LogUsr.Account, EmailCode = EmailCode };
        var LogAuth = new LoginAuth() { Ciphertext = RSA.Encrypt(JsonSerializer.Serialize(emailInfo), publickey!) };
        await AuthService.SendEmailCode(LogAuth);
    }
    private string? PhoneCode { get; set; }
    private async Task SendPhoneCode()
    {
        EmailCode = ShortId.Create(new() { Length=5,OptChars="0123456789"});
        var emailInfo = new GMS.NET.Dto.System.Auth.Input.SendPhone() { Phone = LogUsr.Account, PhoneCode = EmailCode };
        var LogAuth = new LoginAuth() { Ciphertext = RSA.Encrypt(JsonSerializer.Serialize(emailInfo), publickey!) };
        await AuthService.SendPhoneCode(LogAuth);
    }

    //verify
    string accountVerifyText = "";
    string passwordVerifyText = "";
    Color accountVerifyStatus = Color.Info;
    Color passwordVerifyStatus = Color.Info;
    private async Task SubmitAuth()
    {
        var IsAccCount = string.IsNullOrWhiteSpace(LogUsr.Account);
        var IsPassword = string.IsNullOrWhiteSpace(LogUsr.Password);
        if (IsAccCount)
        {
            switch (LogUsr.Mode)
            {
                case LoginType.Default:
                    accountVerifyText = "账号不可为空";
                    break;
                case LoginType.Email:
                    accountVerifyText = "邮箱不可为空";
                    break;
                case LoginType.Phone:
                    accountVerifyText = "手机不可为空";
                    break;
                default:
                    accountVerifyText = "不可为空";
                    break;
            }
            accountVerifyStatus = Color.Danger;
        }
        else
        {
            accountVerifyText = "";
            accountVerifyStatus = Color.Success;
        }
        if (IsPassword)
        {
            switch (LogUsr.Mode)
            {
                case LoginType.Default:
                    passwordVerifyText = "密码不可为空";
                    break;
                case LoginType.Email:
                    passwordVerifyText = "邮箱验证码不可为空";
                    break;
                case LoginType.Phone:
                    passwordVerifyText = "手机验证码不可为空";
                    break;
                default:
                    passwordVerifyText = "不可为空";
                    break;
            }
            passwordVerifyStatus = Color.Danger;
        }
        else
        {
            passwordVerifyText = "";
            passwordVerifyStatus = Color.Success;
        }
        if (IsAccCount || IsPassword) return;

        btnText = "登陆中...";

        if (LogUsr.Mode == LoginType.Email)
        {
            if (LogUsr.Password != EmailCode)
            {
                passwordVerifyText = "邮箱验证码错误";
                passwordVerifyStatus = Color.Danger;
                btnText = "登陆";
                return;
            }
            else
            {
                passwordVerifyText = "";
                passwordVerifyStatus = Color.Success;
            }
        }
        else if (LogUsr.Mode == LoginType.Email)
        {
            if (LogUsr.Password != PhoneCode)
            {
                passwordVerifyText = "手机验证码错误";
                passwordVerifyStatus = Color.Danger;
                btnText = "登陆";
                return;
            }
            else
            {
                passwordVerifyText = "";
                passwordVerifyStatus = Color.Success;
            }
        }
        else
        {
            LogUsr.Password = RSA.Encrypt(LogUsr.Password!, publickey!);
        }

        await Login();
    }

    private async Task Login()
    {
        var LoginAuth = new LoginAuth() { Ciphertext = RSA.Encrypt(JsonSerializer.Serialize(LogUsr), publickey!) };

        var LogResult = await AuthService.LoginAsync(LoginAuth);

        if (LogResult.AccessToken is not null && LogResult.TimeLcs != 0)
        {
            var token = LogResult.AccessToken;

            int randomNumber = DateTime.Now.Day;

            var time = LogResult.TimeLcs / randomNumber;

            await Cookie.SetCookie(ClientAppKey.ServerCookie
                , Protector.CreateProtector(ClientAppKey.ServerCode)
                .Protect(JsonSerializer.Serialize(new InitialUser() { AccessToken = token })), time);

            NavigatTo.NavigateTo("/", true);
        }
        else
        {
            btnText = "登陆";
        }
    }
}